import { FC, PropsWithChildren, useEffect, useRef, useState } from "react";
import { Col, Row, Button, Modal, message, Input } from "antd";
import { FriendSwitchType } from "../type.ts";
import {
  getRecommendFriend,
  getApplyFriends
} from "@/api/xhr/friends/index.ts";
import Card from "@/components/Card";
import AddFriend from "./AddFriend.tsx";
import FriendApply from "./FriendApply.tsx";
import SubmitModal from "./SubmitModal.tsx";
import { useSelector } from "react-redux";
import { makeFriends } from "@/api/xhr/friends/index.ts";
import friendsSocketApiFunc from "@/api/socket/socketFunc/friends.ts";
import { AddFriends } from "@/api/type/socketHandelFuncType.ts";

type typeRecommendFriends = {
  id: number;
  userName: string;
  userAvatar: string;
};
type PropsAddUser = {
  show: boolean;
  setshow: (show: boolean) => void;
};
const controls = {
  isshowtime: false, //是否显示时间
  isshowmessage: false, //是否显示消息
  isnav: false
};
const style = " p-1 border-solid border-2 rounded mr-2 ";

const AddUserCommponent: FC<PropsWithChildren<PropsAddUser>> = ({
  show,
  setshow
}) => {
  const userinfo = useSelector((state: any) => state.user.userinfo);
  const [recommendFriends, setrecommendFriends] = useState<
    (typeRecommendFriends & { show: boolean })[]
  >([]);
  const [aplyfriendlist, setaplyfriendlist] = useState<
    {
      name: string;
      commentInfo: string;
      avatar: string;
      id: number;
    }[]
  >([]);

  const [showComments, SetshowComment] = useState<boolean>(false);
  const [commentInfo, setCommentinfo] = useState<string>("");

  const [FriendSwitch, setFriendSwitch] = useState<number>(
    FriendSwitchType.AddFriend
  );
  const CommentInfo = useRef();

  async function getrecommend() {
    const RecommendFriendres = await getRecommendFriend({});
    const commendFriens: (typeRecommendFriends & { show: boolean })[] =
      RecommendFriendres.data.map((item: typeRecommendFriends) => {
        return {
          id: item.id,
          userName: item.userName,
          userAvatar: item.userAvatar,
          show: true
        };
      });
    setrecommendFriends(commendFriens);
  }
  async function getapply() {
    const ApplyFriendsres = await getApplyFriends({});
    const ApplyFriends = ApplyFriendsres.data?.map(item => {
      return {
        commentInfo: item.commentInfo,
        avatar: item.userAvatar,
        id: item.id,
        name: item.userName
      };
    });
    setaplyfriendlist(ApplyFriends);
  }
  function handelAddfriends(data: AddFriends) {
    const message = data.userName + "向你发送好友请求";
    setrecommendFriends(prevRecommendFriends =>
      prevRecommendFriends.filter(item => item.id !== data.userId)
    );
    setaplyfriendlist(newaplyfriendlist => [
      ...newaplyfriendlist,
      {
        id: data.userId,
        name: data.userName,
        avatar: data.userAvatar,
        commentInfo: data.commentInfo
      }
    ]);
  }

  useEffect(() => {
    Promise.all([getrecommend(), getapply()]);
    // 接管应用 当添加朋友的信息来到时候
    friendsSocketApiFunc.addFriend = handelAddfriends;
    return () => {
      friendsSocketApiFunc.addFriend = () => {};
    };
  }, []);

  function AddFriends(userinfo: any) {
    CommentInfo.current = userinfo;
    SetshowComment(true);
  }

  async function ToAddFriend(
    item: typeRecommendFriends & { commentInfo: string }
  ) {
    const makeFriendres = await makeFriends({
      id1: userinfo.id as number,
      id2: item.id,
      userName: item.userName,
      userAvatar: item.userAvatar,
      commentInfo
    });
    if (makeFriendres.statusCode == 200) {
      SetshowComment(false);
      const newRecommendFriends =
        recommendFriends &&
        (recommendFriends.map(data => {
          if (item.id == data.id) {
            return {
              ...data,
              show: false
            };
          }
          return data;
        }) as (typeRecommendFriends & { show: boolean })[]);
      setrecommendFriends(newRecommendFriends);
      message.success("发送成功，等待对方同意吧");
    }
    setCommentinfo("");
  }

  return (
    <>
      <Modal
        title="🤪好友推荐🤩"
        open={show}
        onCancel={() => setshow(false)}
        footer={null}
        className="p-1"
        width={700}
      >
        <Row className="mt-2" gutter={[8, 0]}>
          <Col span={10} className=" h-96 ">
            <>
              <div className="overflow-y-scroll scrollbar-hide h-full w-full scrollbar select-none cursor-auto border-r-[1px] border-slate-200 ">
                {recommendFriends?.length
                  ? recommendFriends.map(
                      (item: typeRecommendFriends & { show: boolean }) => {
                        return (
                          <Card
                            key={item.userName}
                            item={{
                              id: item.id,
                              avatar: item.userAvatar,
                              name: item.userName
                            }}
                            controls={controls}
                          >
                            <div className="flex">
                              <Button
                                type="link"
                                size="small"
                                className="text-pink-300"
                                disabled={!item.show}
                                onClick={() => AddFriends(item)}
                              >
                                +好友
                              </Button>
                              <Button
                                type="link"
                                size="small"
                                className="p-0 text-sky-300"
                              >
                                发消息
                              </Button>
                            </div>
                          </Card>
                        );
                      }
                    )
                  : "暂无数据"}
              </div>
            </>
          </Col>
          <Col span={14} className="flex flex-col">
            <div className="w-full flex justify-center cursor-pointer h-8">
              <div
                className={
                  FriendSwitch == (FriendSwitchType.AddFriend as unknown)
                    ? "text-sky-300 " + style
                    : " hover:bg-stone-200" + style
                }
                onClick={() => setFriendSwitch(FriendSwitchType.AddFriend)}
              >
                添加好友
              </div>
              <div
                className={
                  FriendSwitch == (FriendSwitchType.VarivfyFriend as unknown)
                    ? "text-sky-300 relative " + style
                    : " hover:bg-stone-200 relative " + style
                }
                onClick={() => setFriendSwitch(FriendSwitchType.VarivfyFriend)}
              >
                {aplyfriendlist.length ? (
                  <i className="absolute -top-1 -right-1 h-[8px] w-[8px] bg-red-400 rounded-[50%]"></i>
                ) : (
                  ""
                )}
                好友申请
              </div>
            </div>
            {FriendSwitch ? (
              <AddFriend AddFriends={AddFriends}></AddFriend>
            ) : (
              <FriendApply
                friendlist={aplyfriendlist}
                setaplyfriendlist={setaplyfriendlist}
              ></FriendApply>
            )}
          </Col>
        </Row>
      </Modal>
      <SubmitModal
        show={showComments}
        changeshow={SetshowComment}
        SubmitFrom={() =>
          ToAddFriend({
            ...(CommentInfo.current as unknown as typeRecommendFriends),
            commentInfo
          })
        }
        subLoading={false}
      >
        <div className="flex justify-center items-center w-full mt-1">
          <div className="w-10 mr-1">留言:</div>
          <Input
            placeholder="填写留言信息"
            onChange={e => {
              return setCommentinfo(e.target.value);
            }}
            value={commentInfo}
          />
        </div>
      </SubmitModal>
    </>
  );
};

export default AddUserCommponent;
